package cdp.tarasenko.task1;

import java.util.Arrays;

/**
* @Author( name = Oleksandr_Tarasenko,
        * date = 27.07.13 )
*/
public class Stack<T> {

    private static final int DEFAULT_SIZE = 16;

    private Object elements[];
    private int capacity;
    private int top = -1;

    public Stack() {
        this(DEFAULT_SIZE);
    }

    public Stack(int initCapacity) {
        if (initCapacity < 0) throw new MyCollectionsException("Value of initial size should not be less than 0.");
        elements = new Object[initCapacity];
        capacity = initCapacity;
    }

    public void push(T item) {
        ensureCapacity();
        top++;
        elements[top] = item;
    }

    public T pull() {
        if (top == -1) throw new MyCollectionsException("You can't pull element from empty stack.");
        T topElement = (T)elements[top];
        top--;
        return topElement;
    }

    public T peek() {
        if (top == -1) throw new MyCollectionsException("You can't peek element from empty stack.");
        return (T)elements[top];
    }

    public int getSize() {
        return top + 1;
    }

    public int getCapacity() {
        return capacity;
    }

    private void ensureCapacity() {
        if ((top + 1) == capacity) {
            int newCapacity = (capacity * 3)/2 + 1;
            Object[] newArray = new Object[newCapacity];
            System.arraycopy(elements, 0, newArray, 0, capacity);
            capacity = newCapacity;
            elements = newArray;
        }
    }
}
